<?php
include 'TurmaController.php';

class AulaController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';



	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
				'accessControl', // perform access control for CRUD operations
		);
	}

	public function actions() {
		return array(
				'frequencia' => array(
						'class' => 'CViewAction',
						'defaultView' => 'frequencia',
				),
				'plano' => array(
						'class' => 'CViewAction',
						'defaultView' => 'plano',
				),
				'avaliacoes' => array(
						'class' => 'CViewAction',
						'defaultView'=> 'avaliacoes',
				),
				'copia' => array(
						'class' => 'CViewAction',
						'defaultView' => 'copia',
				),
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
				array('allow',  // allow all users to perform 'index' and 'view' actions
						'actions'=>array('index', 'copia','view', 'frequencia', 'avaliacoes', 'plano',),
						'users'=>array('@'),
				),
				array('allow', // allow authenticated user to perform 'create' and 'update' actions
						'actions'=>array('create','update'),
						'users'=>array('@'),
				),
				array('allow', // allow admin user to perform 'admin' and 'delete' actions
						'actions'=>array('admin','delete'),
						'users'=>array('@'),
				),
				array('deny',  // deny all users
						'users'=>array('*'),
				),
		);
	}
	
	public function actionCopia($id) {

		$model = $this->loadModel($id);
		$aula = new Aula;
		if(isset($_POST['Aula'])) {
			$aula->attributes = $_POST['Aula'];

			$found = $this->loadModel($aula->numero);
			if($found != null && $found->planos != null) {
				foreach($found->planos as $plano) {
					$newPlan = new Plano;
					$newPlan->texto = $plano->texto;
					$newPlan->tipo = $plano->tipo;
					$newPlan->aula_id = $id;
					$currentPlan = Plano::model()->findByAttributes(array('texto'=> $newPlan->texto, 'tipo'=>$newPlan->tipo, 'aula_id'=>$newPlan->aula_id,));
					if($currentPlan == null) {
						$newPlan->save();
					}
				}
			}

			$this->redirect(array('view','id'=>$id));
				
		}


		$this->render('copia',array(
				'model'=> $model,
				'turma'=>$model->turma,
				'newAula'=>$aula,
		));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);
		$plano = new Plano('search');

		if(isset($_POST['Plano'])) {
			$newPlano = new Plano();
			$newPlano->attributes = $_POST['Plano'];
			$newPlano->aula_id = $id;

			if($newPlano->validate()) {
				$newPlano->save();
			}
			
			$this->redirect(array('view','id'=>$id));
		}

		$this->render('view',array(
				'model'=> $model,
				'turma'=>$model->turma,
				'plano'=>$plano,

		));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionAvaliacoes($id)
	{
		$model = $this->loadModel($id);

		if(isset($_POST['submit'])) {
			foreach($model->turma->turmaHasAlunos as $tuAluno) {

				$avaliacao = new AvaliacaoDiaria();
				$avaliacao->data = $model->data;
				$avaliacao->aula_id = $model->id;
				$avaliacao->turma_has_aluno_id = $tuAluno->id;

				$aux = AvaliacaoDiaria::model()->findByAttributes(array('aula_id'=>$model->id, 'turma_has_aluno_id'=>$tuAluno->id));
				if($aux != null) {
					$avaliacao = $aux;
				}

				if(isset($_POST['texto' . $tuAluno->id])) {
					$avaliacao->texto = $_POST['texto' . $tuAluno->id];

				}
				
				if(isset($_POST['responsavel' . $tuAluno->id])) {
					$avaliacao->responsavel_id = $_POST['responsavel' . $tuAluno->id];
					
				}
				
				if($avaliacao->validate()) {
					$avaliacao->save();
				}
				
			}
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('avaliacoes',array(
				'model'=> $model,
				'turma' => $model->turma,

		));
	}

	public function actionPlano($id) {
		$aula = $this->loadModel($id);
		$this->createAndPrintDocument($aula);

	}


	private function createAndPrintDocument($aula) {
		$ESPACO = "                      ";
		$pdf=new PDF_MC_Table();
		$pdf->Open();
		$pdf->AddPage();
		$pdf->Image('.//css/logo_ufam.jpg',10,7,-150);
		$pdf->Image('.//css/feff.png',182,5,-212);
		$pdf->SetFont('Arial','B',12);
		$pdf->Cell(0,5,'UNIVERSIDADE FEDERAL DO AMAZONAS ',0,1, 'C');
		$pdf->Cell(0,5,utf8_decode('FACULDADE DE EDUCAÇÃO FÍSICA E FISIOTERAPIA'),0,1, 'C');
		$pdf->Ln(10);
			
		$pdf->SetFont('Arial','B',12);
		$pdf->Image('.//css/proamde.png',88,null,-260);
		$pdf->Ln(6);
		$pdf->Cell(0,5,utf8_decode('PLANO DE AULA'),0,1, 'C');
			
		$pdf->Ln(10);
			
		$faixas_etarias = ClasseHasCaracteristica::model()->findAllByAttributes(array('classe_id'=> $aula->turma->classe_id));
		$faixa_etaria = "";
		foreach($faixas_etarias as $faixa) {
			$etaria = Caracteristica::model()->findByPk(array('id'=>$faixa->caracteristica_id));
			if($etaria->tipo == "Idade") {
				$faixa_etaria = $etaria;
				break;
			}
		}
			
		$pdf->Cell(0,8, utf8_decode('Turma: ' . $aula->turma->nome) ,0,1);
		$pdf->Cell(0,8, utf8_decode("Faixa Etária: " .$faixa_etaria->nome),0,1);
		$pdf->Cell(0,8, utf8_decode('Horário: '. $aula->horario),0,1);
		$pdf->Cell(0,8, utf8_decode('Local: '.$aula->local),0,1);
		$pdf->Cell(0,8, utf8_decode('Data: '.$aula->data),0,1);
		$pdf->Cell(0, 8, utf8_decode('Fatores Intercorrentes: '.$aula->fatores),0,1);
			
		$pdf->Ln(10);
		$data = $aula->planos;
		$pdf->SetWidths(array(35, 35, 40, 40, 43));
		
		$pdf->SetFillColor(192,217,217);
		$pdf->SetTextColor(0);
		$pdf->SetDrawColor(0,0,0);
		$pdf->SetLineWidth(.2);
		$pdf->SetFont('','B', 12);
		
		$pdf->Row(array(utf8_decode('Objetivos'), utf8_decode('Conteúdos'), utf8_decode('Procedimentos'), utf8_decode('Recursos'), utf8_decode('Avaliação')));
		$dados = Utils::fancyTable($data, $pdf);
		
		$pdf->SetFillColor(224,235,255);
		$pdf->SetTextColor(0);
		$pdf->SetFont('');
		$pdf->SetFont('Arial','',8);
		
		if($dados != null && !empty($dados)) {
			foreach ($dados as $dado) {
				$pdf->Row($dado);
			}
		}
		
		$pdf->Ln(3);
		$pdf->SetFont('Arial','B',12);
		$pdf->Cell(0, 8, utf8_decode('Observação: '.$aula->observacao),0,1);
		$pdf->Output('plano_de_aula.pdf');
			
		$path = Yii::app()->request->hostInfo . Yii::app()->request->baseURL . '/plano_de_aula.pdf';


		return Yii::app()->getRequest()->sendFile('plano_de_aula_'.$aula->numero.'.pdf', @file_get_contents($path));
	}


	public function actionFrequencia($id) {


		$aula = AulaController::loadModel($id);

		if(isset($_POST['submit'])) {

			foreach($aula->turma->turmaHasAlunos as $tuAluno) {

				$frequencia = new Frequencia;
				$frequencia->data = $aula->data;
				$frequencia->aula_id = $aula->id;
				$frequencia->turma_has_aluno_id = $tuAluno->id;

				$aux = Frequencia::model()->findByAttributes(array('data'=>$aula->data, 'aula_id'=>$aula->id, 'turma_has_aluno_id'=>$tuAluno->id));

				if($aux != null) {
					$frequencia = $aux;
				}

				if(isset($_POST['new_check'.$tuAluno->aluno_id])) {
					$result = $_POST['new_check'.$tuAluno->aluno_id];
					$frequencia->resposta = $result;
				}

				$frequencia->save();
			}

			$this->redirect(array('view','id'=>$aula->id));
		}


		$this->render('frequencia',array(
				'aula'=>$aula,
		));

	}


	public function createTabelaAvaliacao($form, $aula) {
		if($aula->turma->turmaHasAlunos != null) {
			echo '<br/><br/><Table style="background-color:#9AE6DA; padding:5px; border: 1px solid #bbbbbb;">';
			echo "<TR>";
			echo '<TD style:"padding:5px; border: 1px solid #bbbbbb;"><h4  align="center"> Alunos </h4></TD>';
			echo '<TD style:"padding:5px; border: 1px solid #bbbbbb;"><h4 align="center">Avaliação</h4></TD>';
			echo '<TD style:"padding:5px; border: 1px solid #bbbbbb;"><h4 align="center">Responsável</h4></TD>';
			echo '</TR>';
			foreach($aula->turma->turmaHasAlunos as $aluno) {
				$texto = "";
				$avaliacao = AvaliacaoDiaria::model()->findByAttributes(array('aula_id'=>$aula->id, 'turma_has_aluno_id'=>$aluno->id));
				if($avaliacao == null) {
					$avaliacao = new AvaliacaoDiaria;
					$avaliacao->texto = "";
				}

				echo '<TR>';
				echo '<TD style:"padding:5px; border: 1px solid #bbbbbb; width:100px;"><p align="center" class="span3">';
				echo $aluno->aluno->pessoa->nome;
				echo '</p></TD>';
				echo '<TD style:"padding:5px; border: 1px solid #bbbbbb;"><h6>';
				echo $form->textField($avaliacao, 'texto', array('class'=>'span3','name' => 'texto' . $aluno->id, 'value' => $avaliacao->texto ,'size' => 250, 'maxlength' => 80));
				echo '</TD class="td">';
				echo '<TD style:"padding:5px; border: 1px solid #bbbbbb;"><h6>';
				
				$funcionarios = Funcionario::model()->findAllByAttributes(array('polo_id' => Yii::app()->session['polo_id']));
				$data = array();
				
				foreach ($funcionarios as $funcionario) {
					$pessoa = Pessoa::model()->findByAttributes(array('id'=>$funcionario->pessoa_id));
					if($funcionario->id != 1) {
						$data[$funcionario->id] = $pessoa->nome;
					}
				}
				echo $form->dropDownList($avaliacao, 'responsavel_id', $data, array('class'=>'span2', 'name' => 'responsavel' . $aluno->id, 'empty' => ''));
				
				echo '</TD class="td">';
				echo '</TR>';
			}

			echo "</Table>";
			echo '<br/><h4 align="center">';
			$this->widget('bootstrap.widgets.TbButton', array(
					'buttonType'=>'submit',
					'type'=>'primary',
					'label' => 'Concluir',
					'htmlOptions' => array('name' => 'submit','class' => 'ui-button-primary')
			));
			echo "</h4>";
		}  else {
			echo '<h4 align="center">Não há alunos matriculados para a Avaliação</h4>';
		}
	}


	public function createTable($form, $aula) {
		if($aula->turma->turmaHasAlunos != null) {
			$item = new Frequencia;
			echo '<br/><Table style="padding:5px; border: 1px solid #bbbbbb;">';
			echo '<TR style="padding:5px; border: 1px solid #bbbbbb;">';
			echo '<TD style="padding:5px; border: 1px solid #bbbbbb; width:500px;"><h4  align="center"> '.Aluno::getModuleName().'s </h4></TD>';
			echo '<TD style="padding:5px; border: 1px solid #bbbbbb;"><h4  align="center">Presente</h4></TD>';
			echo '<TD style="padding:5px; border: 1px solid #bbbbbb;"><h4  align="center">Ausente</h4></TD>';
			echo '</TR>';
			foreach($aula->turma->turmaHasAlunos as $aluno) {
				$presente = false;
				$frequencia = Frequencia::model()->findByAttributes(array('data'=>$aula->data, 'aula_id'=>$aula->id, 'turma_has_aluno_id'=>$aluno->id));
				if($frequencia != null && $aluno->frequencias != null && in_array($frequencia, $aluno->frequencias)) {
					$presente = $frequencia->resposta == 'Sim' ? true : false;
				}
				$background = '#000000';
				$adicional = '';
				if($aluno->status != 'Ativo') {
					$background= '#999999';
					$adicional = ' ('.$aluno->status.')';
				}
				//space for all frequences
				echo '<TR style="padding:5px; border: 1px solid #bbbbbb;">';
				echo '<TD align="center" style="padding:5px; border: 1px solid #bbbbbb;">';
				echo '<p  align="center" style="color:'.$background.';":>'.$aluno->aluno->pessoa->nome;
				echo $adicional.'</p>';
				echo '</TD>';

				//space for new frequencia
				echo '<TD style="padding:5px; border: 1px solid #bbbbbb;"><h6 align="center">';
				echo $form->radioButton($item, 'id', array(
						'name' => 'new_check'.$aluno->aluno_id,
						'value' => 'Sim',
						'checked' => $presente ? '1' : '0',
						'uncheckValue' => null)) . ' ';
				echo '</h6></TD>';
				echo "<TD>";
				echo '<p align="center">'.$form->radioButton($item, 'item', array(
						'name' => 'new_check'.$aluno->aluno_id,
						'value' => 'Não',
						'checked' => $presente ? '0' : '1',
						'uncheckValue' => null)) . ' </p>';
				echo '</TD>';
				echo '</TR>';
			}
			echo "</Table>";

			echo '<br/><h4 align="center">';
			$this->widget('bootstrap.widgets.TbButton', array(
					'buttonType'=>'submit',
					'type'=>'primary',
					'label' => 'Concluir',
					'htmlOptions' => array('name' => 'submit','class' => 'ui-button-primary')
			));

			echo"<br/></h4>";
		} else {
			echo '<h4 align="center">Não há '.Aluno::getModuleName().'s matriculados para a Frequência</h4>';
		}
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($id)
	{
		$model=new Aula;
		$turma = TurmaController::loadModel($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Aula']))
		{
			$model->attributes=$_POST['Aula'];
			$model->turma_id = $id;
			$correct = true;
			$numero = 1;
			if($turma->aulas != null && $model->data != null) {
				$numero = sizeof($turma->aulas) + 1;
				foreach($turma->aulas as $aula) {
					if($aula ==$model->data) {
						$correct = false;
					}
				}
			}

			$model->numero = $numero;
			if($correct && $model->validate()) {
				$model->save();
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('create',array(
				'model'=>$model,
				'turma'=>$turma,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Aula']))
		{
			$model->attributes=$_POST['Aula'];
			if($model->validate()) {
				$model->save();
				$this->saveFrequenciaDatas($model);
				$this->saveAvaliacaoDiariaDatas($model);
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('update',array(
				'model'=>$model,
				'turma' =>$model->turma,
		));
	}
	
	private function saveFrequenciaDatas($model) {
		$frequencias = Frequencia::model()->findAllByAttributes(array('aula_id'=>$model->id));
		if($frequencias != null && !empty($frequencias)) {
			foreach($frequencias as $frequencia) {
				$frequencia->data = $model->data;
				$frequencia->save();
			}
		}
	}
	
	private function saveAvaliacaoDiariaDatas($model) {
		$avaliacoes = AvaliacaoDiaria::model()->findAllByAttributes(array('aula_id'=>$model->id));
		if($avaliacoes != null && !empty($avaliacoes)) {
			foreach($avaliacoes as $avaliacao) {
				$avaliacao->data = $model->data;
				$avaliacao->save();
			}
		}
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel($id);
			$turma_id = $model->turma_id;
			$model->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('/turma/view', 'id'=>$turma_id));
		}
		else
			throw new CHttpException(400,'Pedido inválido, solicite novamente.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex($id)
	{

		$model = $this->loadModel($id);

		$this->render('view',array(
				'model'=> $model,
				'turma'=>$model->turma,

		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin($id)
	{
		$turma= TurmaController::loadModel($id);

		$model=new Aula('search');

		$model->unsetAttributes();
		$this->render('admin',array(
				'model'=>$model,
				'turma'=>$turma,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public static function loadModel($id)
	{
		$model=Aula::model()->findByPk($id);
		$model->turma = TurmaController::loadModel($model->turma_id);
		$model->planos = Plano::model()->findAllByAttributes(array('aula_id'=>$id));
		$model->frequencias = Frequencia::model()->findByAttributes(array('aula_id'=>$id));
		$model->avaliacaoDiarias = AvaliacaoDiaria::model()->findAllByAttributes(array('aula_id'=>$id));

		if($model===null)
			throw new CHttpException(404,'A página buscada não existe.');
		return $model;
	}


	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='aula-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
